package com.dao.impl;

import com.util.HibernateUtil;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.dao.ActionDAO;
import com.rev.Action;
import com.rev.ActionHome;
import com.rev.Automaticintervention;
import com.rev.Sourcetype;
import com.rev.TargetHome;
import com.rev.TargettypeHome;

public class ActionDAOImpl implements ActionDAO{
	private ActionHome ah = new ActionHome(); 
	private TargetHome th = new TargetHome(); 
	private TargettypeHome tth = new TargettypeHome(); 

	public boolean insert(Action action) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction  transaction = session.beginTransaction();
			if(tth.findById(action.getTarget().getTargettype().getIdtargetType()) == null)
				tth.attachDirty(action.getTarget().getTargettype());
			if(th.findById(action.getTarget().getIdTarget()) == null)
				th.attachDirty(action.getTarget());
			ah.attachDirty(action);
			transaction.commit();
			session.close();
			return true;
		} catch (Exception e) {}
		return false;
	}

	public boolean update(Action action) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction  transaction = session.beginTransaction();
			ah.attachDirty(action);
			transaction.commit();
			session.close();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}

	public boolean delete(Action action) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction  transaction = session.beginTransaction();
			ah.delete(action);
			transaction.commit();
			session.close();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}

	public Action findById(int id) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			Action s = ah.findById(id);
			session.getTransaction().commit();
			session.close();
			return s;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	public List<Automaticintervention> findAutomaticInterventions(Action action) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public List<Action> findAll() {

		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			List list = ah.findByExample(new Action());
			session.getTransaction().commit();
			session.close();
			return list;
		} catch (Exception e) {
		}
		return null;
	}


}
